package models

import(
	"time"
	"log"
	"errors"
	"fmt"
	"github.com/astaxie/beego/orm"
	"github.com/astaxie/beego/validation"
)

//登陆用户的账户信息
type User struct{
	Id int64    `orm:"auto"`   //主键
	Name string  
	Password string
	CreatedAt time.Time  //创建时间
	LastloginAt time.Time  //上次登录时间

}

func checkUser(u *User) (err error){
	valid:=validation.Validation{}
	b,_:=valid.Valid(&u)
	if !b{
		for _,err := range valid.Errors{
			log.Println(err.Key,err.Message)
			return errors.New(err.Message)
		}
	}
	return nil
}


//添加用户
func AddUser(u *User) (int64 ,error){
	if err:=checkUser(u); err !=nil{
		return 0,err
	}
	o:=orm.NewOrm()
	user:=new(User)
	user.Name=u.Name
	user.Password=u.Password   //Stromd5(u.Password)
	user.CreatedAt=time.Now()
	user.LastloginAt=time.Now()

	id,err:=o.Insert(user)
	return id,err
}

//按名字查找用户
func GetUserByName(username string) (user User){
	user=User{Name:username}
	o:=orm.NewOrm()
	o.Read(&user,"name")
	return user
}


func QueryByName(name string) (User,error){
	var user User
	o:=orm.NewOrm()
	qs:=o.QueryTable("user")
	err:=qs.Filter("name",name).One(&user)
	fmt.Println(err)
	if err == nil {     //没有错误
		fmt.Println(user.Name)
		return user,nil
	}
	return user,err

}


//删除用户
func DelUserById(Id int64) (int64,error){
	o:=orm.NewOrm()
	status,err:=o.Delete(&User{Id:Id})
	return status,err
}







func init(){
	orm.RegisterModel(new(User))
}
